import CryptoJS from 'crypto-js';
import TokenManager from '@/token';
import { flushSync } from 'react-dom';
import type { API } from '@/types/api';
import { Alert, App, Tabs } from 'antd';
import React, { useState } from 'react';
import { createStyles } from 'antd-style';
import { login } from '@/services/core/api';
import { Helmet, SelectLang, useIntl, useModel } from '@umijs/max';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';

const Login: React.FC = () => {
    // useEffect(() => {
    //     const checkTokenAndRedirect = async () => {
    //         const token = TokenManager.getAccessToken();
    //         if (token) {
    //             try {
    //                 const isValid = await postVerifyToken();
    //                 if (isValid) {
    //                     // const urlParams = new URL(window.location.href).searchParams;
    //                     // window.location.href = urlParams.get('redirect') || '/hosting';
    //                     // TIPS 跳转到hosting
    //                     window.location.href = '/hosting';
    //                 } else {
    //                     localStorage.clear();
    //                 }
    //             } catch (error) {
    //                 console.log('Token验证失败:', error);
    //                 localStorage.clear();
    //             }
    //         }
    //     };

    //     checkTokenAndRedirect();
    // }, []);

    const useStyles = createStyles(({ token }) => {
        return {
            action: {
                marginLeft: '8px',
                color: 'rgba(0, 0, 0, 0.2)',
                fontSize: '24px',
                verticalAlign: 'middle',
                cursor: 'pointer',
                transition: 'color 0.3s',
                '&:hover': {
                    color: token.colorPrimaryActive,
                },
            },
            lang: {
                width: 42,
                height: 42,
                lineHeight: '42px',
                position: 'fixed',
                right: 16,
                borderRadius: token.borderRadius,
                ':hover': {
                    backgroundColor: token.colorBgTextHover,
                },
            },
            container: {
                display: 'flex',
                flexDirection: 'column',
                height: '100vh',
                overflow: 'auto',
                // TIPS 登录界面背景图
                backgroundImage: "url('/assets/login_background.png')",
                backgroundSize: '100% 100%',
            },
        };
    });

    const Lang = () => {
        const { styles } = useStyles();

        return (
            <div className={styles.lang} data-lang>
                {SelectLang && <SelectLang />}
            </div>
        );
    };

    const LoginMessage: React.FC<{
        content: string;
    }> = ({ content }) => {
        return (
            <Alert
                style={{
                    marginBottom: 24,
                }}
                message={content}
                type="error"
                showIcon
            />
        );
    };
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({
        message: {
            access_token: '',
            refresh_token: '',
            uid: '',
        },
        status: 'success',
        status_code: '',
    });
    const [type, setType] = useState<string>('account');
    const { initialState, setInitialState } = useModel('@@initialState');
    const { styles } = useStyles();
    const { message } = App.useApp();
    const intl = useIntl();

    const fetchUserInfo = async () => {
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
            flushSync(() => {
                setInitialState((s) => ({
                    ...s,
                    currentUser: userInfo,
                }));
            });
        }
    };

    const handleSubmit = async (values: API.LoginParams) => {
        try {
            // 登录
            const encryptedValues = { ...values };
            if (encryptedValues.password) {
                // 对密码进行 MD5 加密
                encryptedValues.password = CryptoJS.MD5(encryptedValues.password).toString();
            }
            const msg = await login({ ...encryptedValues, type });
            if (msg.status === 'success') {
                const defaultLoginSuccessMessage = '登录成功';
                TokenManager.saveAccessToken(msg.message.access_token);
                TokenManager.saveRefreshToken(msg.message.refresh_token);
                localStorage.setItem('USER_UID', msg.message.uid);
                message.success(defaultLoginSuccessMessage);
                await fetchUserInfo();
                // const urlParams = new URL(window.location.href).searchParams;
                // window.location.href = urlParams.get('redirect') || '/hosting';
                // TIPS 跳转到hosting
                window.location.href = '/hosting';
                return;
            }
            console.log('结果：', msg);
            // 如果失败去设置用户错误信息
            setUserLoginState(msg);
        } catch (error) {
            const defaultLoginFailureMessage = '登录失败，请重试！';
            console.log(error);
            message.error(defaultLoginFailureMessage);
        }
    };
    const { status } = userLoginState;

    return (
        <div className={styles.container}>
            <Helmet>
                <title>登录页</title>
            </Helmet>
            <Lang />
            <div
                style={{
                    flex: '1',
                    padding: '32px 0',
                }}
            >
                <LoginForm
                    contentStyle={{
                        minWidth: 280,
                        maxWidth: '75vw',
                    }}
                    logo={<img alt="logo" src="/icons/FisherMan.png" />}
                    title="渔翁"
                    subTitle={' '}
                    initialValues={{
                        autoLogin: true,
                    }}
                    // actions={[
                    //     <FormattedMessage
                    //         key="loginWith"
                    //         id="pages.login.loginWith"
                    //         defaultMessage="其他登录方式"
                    //     />,
                    //     <ActionIcons key="icons" />,
                    // ]}
                    onFinish={async (values) => {
                        await handleSubmit(values as API.LoginParams);
                    }}
                >
                    <Tabs
                        activeKey={type}
                        onChange={setType}
                        centered
                        items={[
                            {
                                key: 'account',
                                label: '账户密码登录',
                            },
                            // {
                            //     key: 'mobile',
                            //     label: intl.formatMessage({
                            //         id: 'pages.login.phoneLogin.tab',
                            //         defaultMessage: '手机号登录',
                            //     }),
                            //     disabled: true,
                            // },
                        ]}
                    />

                    {status === 'error' && <LoginMessage content={'账户或密码错误'} />}

                    {type === 'account' && (
                        <>
                            <ProFormText
                                name="username"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined />,
                                }}
                                placeholder={'用户名'}
                                rules={[
                                    {
                                        required: true,
                                        message: <>请输入用户名！</>,
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                name="password"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined />,
                                }}
                                placeholder={'密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: <>请输入密码！</>,
                                    },
                                ]}
                            />
                        </>
                    )}

                    {status === 'error' && <LoginMessage content="验证码错误" />}
                    {type === 'mobile' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: <MobileOutlined />,
                                }}
                                name="mobile"
                                placeholder={'手机号'}
                                rules={[
                                    {
                                        required: true,
                                        message: <>请输入手机号！</>,
                                    },
                                    {
                                        pattern: /^1\d{10}$/,
                                        message: <>手机号格式错误！</>,
                                    },
                                ]}
                            />
                            {/* <ProFormCaptcha
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined />,
                                }}
                                captchaProps={{
                                    size: 'large',
                                }}
                                placeholder={intl.formatMessage({
                                    id: 'pages.login.captcha.placeholder',
                                    defaultMessage: '请输入验证码',
                                })}
                                captchaTextRender={(timing, count) => {
                                    if (timing) {
                                        return `${count} ${intl.formatMessage({
                                            id: 'pages.getCaptchaSecondText',
                                            defaultMessage: '获取验证码',
                                        })}`;
                                    }
                                    return intl.formatMessage({
                                        id: 'pages.login.phoneLogin.getVerificationCode',
                                        defaultMessage: '获取验证码',
                                    });
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: (
                                            <FormattedMessage
                                                id="pages.login.captcha.required"
                                                defaultMessage="请输入验证码！"
                                            />
                                        ),
                                    },
                                ]}
                                onGetCaptcha={async (phone) => {
                                    const result = await getFakeCaptcha({
                                        phone,
                                    });
                                    if (!result) {
                                        return;
                                    }
                                    message.success('获取验证码成功！验证码为：1234');
                                }}
                            /> */}
                        </>
                    )}
                    <div
                        style={{
                            marginBottom: 24,
                        }}
                    >
                        {/* <ProFormCheckbox noStyle name="autoLogin">
                            <FormattedMessage
                                id="pages.login.rememberMe"
                                defaultMessage="自动登录"
                            />
                        </ProFormCheckbox> */}
                        {/* <a
                            style={{
                                float: 'right',
                            }}
                        >
                            <FormattedMessage
                                id="pages.login.forgotPassword"
                                defaultMessage="忘记密码"
                            />
                        </a> */}
                    </div>
                </LoginForm>
            </div>
            {/* <Footer /> */}
        </div>
    );
};

export default Login;
